//
//  ShareViewController.swift
//  Boom
//
//  Created by joker on 15/7/23.
//  Copyright (c) 2015年 joker. All rights reserved.
//

import UIKit
import Social

import MobileCoreServices

class ShareViewController: SLComposeServiceViewController ,  NSURLSessionDelegate,AudienceSelectionViewControllerDelegate{
    
    var imageData: NSData?
    
    override func presentationAnimationDidFinish() {
        super.presentationAnimationDidFinish()
        
        placeholder = "Your comments"
        
        let content = extensionContext!.inputItems[0] as! NSExtensionItem
        
        let contentType = kUTTypeImage as NSString
        
        for attachment in content.attachments as! [NSItemProvider] {
            if attachment.hasItemConformingToTypeIdentifier(contentType as String) {
                
                let dispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0 )
                dispatch_async(dispatchQueue, {[weak self] in
                    let strongSelf = self!
                    
                    attachment.loadItemForTypeIdentifier(contentType as String,options:nil,
                        completionHandler: {
                            (content: NSSecureCoding!, error: NSError!) in
                            if let data = content as? NSData {
                                dispatch_async(dispatch_get_main_queue(), {
                                    strongSelf.imageData = data
                                    strongSelf.validateContent()
                                    
                                })
                            }
                    })
                    })
            }
            break
        }
    }
    override func isContentValid() -> Bool {
        // Do validation of contentText and/or NSExtensionContext attachments here
        if let data = imageData {
            if count(contentText) > 0 {
                return true
            }
        }
        return false
    }
    
    override func didSelectPost() {
        // This is called after the user selects Post. Do the upload of contentText and/or NSExtensionContext attachments.
        
        // Inform the host that we're done, so it un-blocks its UI. Note: Alternatively you could call super's -didSelectPost, which will similarly complete the extension context.
        let identifier = NSBundle.mainBundle().bundleIdentifier! + "." + NSUUID().UUIDString
        
        let configuration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier(identifier)
        
        let session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: nil)
        
        let url = NSURL(string: "https://www.baidu.com/&text=" + self.contentText)
        
        let request = NSMutableURLRequest(URL: url!)
        
        request.HTTPMethod = "POST"
        request.HTTPBody = imageData!
        
        let task = session.uploadTaskWithRequest(request,fromData: request.HTTPBody)
        task.resume()
        
        self.extensionContext!.completeRequestReturningItems([], completionHandler: nil)
        
    }
    
    lazy var audienceConfigurationItem: SLComposeSheetConfigurationItem = {
        let item = SLComposeSheetConfigurationItem()
        item.title = "Audience"
        item.value = AudienceSelectionViewController.defaultAudience()
        item.tapHandler = self.showAudienceSelection
        return item
        }()
    
    override func configurationItems() -> [AnyObject]! {
        // To add configuration options via table cells at the bottom of the sheet, return an array of SLComposeSheetConfigurationItem here.
        return [audienceConfigurationItem]
    }
    func showAudienceSelection(){
        let controller = AudienceSelectionViewController(style: .Plain)
        controller.audience = audienceConfigurationItem.value
        controller.delegate = self
        pushConfigurationViewController(controller)
    }
    
    func audienceSelectionViewController(sender: AudienceSelectionViewController, selectedValue: String) {
        audienceConfigurationItem.value = selectedValue
        popConfigurationViewController()
    }
}

@objc(AudienceSelectionViewControllerDelegate)
protocol AudienceSelectionViewControllerDelegate {
    optional func audienceSelectionViewController(sender: AudienceSelectionViewController,
        selectedValue: String)
}

class AudienceSelectionViewController: UITableViewController {
    struct TableViewValues {
    static let identifier = "Cell"
    }
    
    enum Audience: String {
        case Everyone = "Everyone"
        case Family = "Family"
        case Friends = "Friends"
        static let allValues = [Everyone, Family, Friends]
    }
    
    var delegate: AudienceSelectionViewControllerDelegate?
    
    var audience = Audience.Everyone.rawValue
    
    class func defaultAudience() -> String {
        return Audience.Everyone.rawValue
    }
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return Audience.allValues.count
    }
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(TableViewValues.identifier, forIndexPath: indexPath) as! UITableViewCell
        let text = Audience.allValues[indexPath.row].rawValue
        
        cell.textLabel!.text = text
        
        if text == audience {
            cell.accessoryType = .Checkmark
        } else {
            cell.accessoryType = .None
        }
        return cell
    }
    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        let selectedAudience = Audience.allValues[indexPath.row].rawValue
        self.delegate!.audienceSelectionViewController!(self,selectedValue: selectedAudience)
    }
    
    required init(coder aDecoder: NSCoder) {
        super.init(coder:aDecoder)
    }
    
    override init(style: UITableViewStyle) {
        super.init(style:style)
        tableView.registerClass(UITableViewCell.classForCoder(),forCellReuseIdentifier: TableViewValues.identifier )
        title = "Choose Audience"
    }
    
    override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }
}


